import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:qrcode_reader/qrcode_reader.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:zchope_student/apis.dart';
import 'package:zchope_student/beans/queryStudentBean.dart';
import 'package:zchope_student/beans/regionCityBean.dart';
import 'package:zchope_student/const.dart';
import 'package:zchope_student/utils/mydio.dart';
import 'package:zchope_student/utils/utils.dart';

class Lessons extends StatefulWidget {
  @override
  _LessonsState createState() => _LessonsState();
}

class _LessonsState extends State<Lessons> {
  int _selectedMenu = 99;
  int _selectedPart = 99;
  int _selectedSubject = 99;
  var kcfsCode = '';
  var pxbfCode = '';
  var pxxmCode = '';
  var pxcxCode = '';
  var cityName = ''; //城市名称
  var IdNum = ''; //身份证号
  var stuName = ''; //学员姓名
  var stuNum = ''; //学员id
  Future<String> _barcodeString;

//  var _menu = ['实操', '模拟'];

  static var _menu1 = const {'title': '实操', 'index': '1'};
  static var _menu2 = const {'title': '模拟', 'index': '3'};
  var _menu = [_menu1, _menu2];

  List<String> _menu1_1 = ['第二部分', '第三部分'];

//  List<String> _menu1_2 = ['第一部分', '第四部分'];

  var _subPart = List();
  var _subSubject = List();

  var _menuForIndexTwo = ["基础驾驶", "场地驾驶", "第二部分综合驾驶及考核"];
  var _menuForIndexThree = [
    "跟车行驶",
    "变更车道",
    "靠边停车",
    "掉头",
    "通过路口",
    "通过人行横道",
    "通过学校区域",
    "通过公共汽车站",
    "会车",
    "超车",
    "夜间驾驶",
    "恶劣条件下的驾驶",
    "山区道路驾驶",
    "高速公路驾驶",
    "行驶路线选择",
    "第三部分综合驾驶及考核"
  ];

  Iterable<Widget> get actorWidget sync* {
    for (int i = 0; i < _menu.length; i++) {
      yield Padding(
        padding: const EdgeInsets.symmetric(horizontal: 8),
        child: ChoiceChip(
          backgroundColor: Const.grey,
          selectedColor: Const.gold,
          disabledColor: Const.grey,
          label: Text((_menu[i])['title']),
          labelStyle: TextStyle(fontSize: 15, color: Colors.white),
          labelPadding: EdgeInsets.only(left: 20, right: 20),
          materialTapTargetSize: MaterialTapTargetSize.padded,
          onSelected: (bool value) {
            setState(() {
              _selectedMenu = i;
              kcfsCode = (_menu[i])['index'];
              print('_selectedMenu:$_selectedMenu');
              _selectedPart = 99;
              _selectedSubject = 99;
              _subSubject = List();
              if (i == 0) {
                _subPart = _menu1_1;
              } else {
                _subPart = _menu1_1;
              }
            });
          },
          selected: _selectedMenu == i,
        ),
      );
    }
  }

  Iterable<Widget> get actorWidgetPart sync* {
    for (int i = 0; i < _subPart.length; i++) {
      yield Padding(
        padding: const EdgeInsets.symmetric(horizontal: 8),
        child: ChoiceChip(
          backgroundColor: Const.grey,
          selectedColor: Const.gold,
          disabledColor: Const.grey,
          label: Text(_subPart[i]),
          labelStyle: TextStyle(fontSize: 15, color: Colors.white),
          labelPadding: EdgeInsets.only(left: 20, right: 20),
          materialTapTargetSize: MaterialTapTargetSize.padded,
          onSelected: (bool value) {
            setState(() {
              _selectedPart = i;
              _selectedSubject = 99;
              pxbfCode = '${i + 2}';
              print('_selectedPart:$_selectedPart');
              if (i == 0) {
                _subSubject = _menuForIndexTwo;
              } else {
                _subSubject = _menuForIndexThree;
              }
            });
          },
          selected: _selectedPart == i,
        ),
      );
    }
  }

  Iterable<Widget> get actorWidgetSubject sync* {
    for (int i = 0; i < _subSubject.length; i++) {
      yield Padding(
        padding: const EdgeInsets.symmetric(horizontal: 8),
        child: ChoiceChip(
          backgroundColor: Const.grey,
          selectedColor: Const.gold,
          disabledColor: Const.grey,
          label: Text(_subSubject[i]),
          labelStyle: TextStyle(fontSize: 15, color: Colors.white),
          labelPadding: EdgeInsets.only(left: 20, right: 20),
          materialTapTargetSize: MaterialTapTargetSize.padded,
          onSelected: (bool value) {
            setState(() {
              _selectedSubject = i;
              if (pxbfCode == '2') {
                pxxmCode = '${i + 11}';
              } else if (pxbfCode == '3') {
                pxxmCode = '${i + 21}';
              }
              print('_selectedSubject:$_selectedSubject');
            });
          },
          selected: _selectedSubject == i,
        ),
      );
    }
  }

  Future<Null> _connectBLE(String terminalId) async {
    Map<String, dynamic> jsonData = Map();
    jsonData['p3'] = IdNum;
    jsonData['p2'] = stuName;
    jsonData['p1'] = stuNum;
    jsonData['p4'] = kcfsCode + pxcxCode + pxbfCode + pxxmCode + '0000';
    jsonData['p5'] =
        DateTime.now().millisecondsSinceEpoch.toString().substring(0, 6);
    print(DateTime.now().millisecondsSinceEpoch);
    Map<String, String> map = {
      "deviceName": terminalId,
      "data": json.encode(jsonData)
    };
    String result = await Const.jumpPlugin.invokeMethod('oneAct', map);
    print(result);
    if (result == 'successToConnect') {
      print('收到返回信息');
      Navigator.pop(context);
    }
//    print(json.encode(jsonData));
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _getCityName();
  }

  _getCityName() async {
    SharedPreferences sp = await SharedPreferences.getInstance();
    cityName = Utils.getInstance().getCityName(sp.getString('areacode'));
    _getUrl();
  }

  _getUrl() {
    MyDio.getInstance().clearInstance();
    MyDio.getInstance(url: Const.BASEURL)
        .get('${Apis.getRegionByCity}$cityName', (data) async {
      print(data);
      if (data['resultCode'] == 0) {
        RegionCityBean regionCityBean = RegionCityBean.fromJson(data['record']);
        if (regionCityBean.trainingurl.isNotEmpty) {
          print(regionCityBean.trainingurl);
          queryStudentInfo(regionCityBean.trainingurl);
        }
      }
    });
  }

  queryStudentInfo(String trainingurl) async {
    SharedPreferences sp = await SharedPreferences.getInstance();
    String personNum = sp.getString(Const.PERSON_NUM);
    MyDio.getInstance().clearInstance();
    MyDio.getInstance(url: trainingurl).get('${Apis.getStudent}$personNum',
        (data) async {
      if (data['resultCode'] == 0) {
        QueryStudentBean queryStudentBean =
            QueryStudentBean.fromJson(data['record']);
        String cartype = queryStudentBean.cartype;
        IdNum = queryStudentBean.personNum;
        stuName = queryStudentBean.name;
        stuNum = queryStudentBean.stunum;
        queryCarTypeCode(cartype);
      }
    });
  }

  /**
   * 查询车辆类型
   */
  queryCarTypeCode(String cartype) {
    switch (cartype) {
      case "无":
        pxcxCode = "00";
        break;
      case "A1":
        pxcxCode = "01";
        break;
      case "A2":
        pxcxCode = "02";
        break;
      case "A3":
        pxcxCode = "03";
        break;
      case "B1":
        pxcxCode = "11";
        break;
      case "B2":
        pxcxCode = "12";
        break;
      case "C1":
        pxcxCode = "21";
        break;
      case "C2":
        pxcxCode = "22";
        break;
      case "C3":
        pxcxCode = "23";
        break;
      case "C4":
        pxcxCode = "24";
        break;
      case "C5":
        pxcxCode = "25";
        break;
      case "D":
        pxcxCode = "31";
        break;
      case "E":
        pxcxCode = "32";
        break;
      case "F":
        pxcxCode = "33";
        break;
      case "M":
        pxcxCode = "41";
        break;
      case "N":
        pxcxCode = "42";
        break;
      case "P":
        pxcxCode = "43";
        break;
    }
    print(pxcxCode + '====' + cartype);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Const.black,
      appBar: AppBar(
        backgroundColor: Colors.transparent,
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          Expanded(
            child: ListView(
              padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
              children: <Widget>[
                SizedBox(height: 5),
                Text(
                  '课程方式',
                  style: TextStyle(fontSize: 12, color: Const.gold),
                ),
                Row(
                  children: actorWidget.toList(),
                ),
                Divider(
                  height: 1,
                  color: Const.grey,
                ),
                SizedBox(height: 5),
                Text(
                  '培训部分',
                  style: TextStyle(fontSize: 12, color: Const.gold),
                ),
                actorWidgetPart.length == 0
                    ? Container()
                    : Row(
                        children: actorWidgetPart.toList(),
                      ),
                Divider(
                  height: 1,
                  color: Const.grey,
                ),
                SizedBox(height: 5),
                Text(
                  '培训项目',
                  style: TextStyle(fontSize: 12, color: Const.gold),
                ),
                actorWidgetSubject.length == 0
                    ? Container()
                    : Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: actorWidgetSubject.toList(),
                      )
              ],
            ),
          ),
          MaterialButton(
            height: 68,
            minWidth: MediaQuery.of(context).size.width,
            elevation: 0,
            onPressed: () {
              setState(() {
                _barcodeString = QRCodeReader()
                    .setAutoFocusIntervalInMs(200)
                    .setForceAutoFocus(true)
                    .setTorchEnabled(true)
                    .setHandlePermissions(true)
                    .setExecuteAfterPermissionGranted(true)
//                    .setFrontCamera(false)
                    .scan();

                _barcodeString.then((String value) {
                  print('qrcode:$value');
                  if (value.isNotEmpty) {
                    String terminalId =
                        Utils.getInstance().getTerminalId(value);
                    _connectBLE(terminalId);
                  }
                });
              });
//                _connectBLE('13333333333');
//
              print(kcfsCode + pxcxCode + pxbfCode + pxxmCode + '0000');
            },
            child: Text(
              "开始学习",
              style: TextStyle(color: Colors.white, fontSize: 20),
            ),
            color: Const.gold,
            shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.only(
                    topLeft: Radius.circular(30),
                    bottomRight: Radius.circular(30))),
          ),
        ],
      ),
    );
  }
}
